# -*- coding: utf-8 -*-
from flask import g
from flask import jsonify, abort, request
from flask import url_for

from .errors import forbidden
from ..models import User
from .authentication import auth
from . import api
from .. import db


@api.route('/users/<email>')
@auth.login_required
def get_user(email):
    user = User.query.filter_by(username=email).first()
    if user is None:
        abort(404)
    return jsonify(user.to_json())


@api.route('/users/', methods=['post'])
def new_user():
    user = User.from_json(request.get_json())
    db.session.add(user)
    db.session.commit()
    return jsonify({'error': '0', 'message': u'注册成功。'})


@api.route('/users/mpasswd/', methods=['post'])
@auth.login_required
def modify_password():
    data = request.get_json()

    if g.current_user.verify_password(data['old_password']):
        g.current_user.password = data['new_password']
        db.session.add(g.current_user)
        db.session.commit()
        return jsonify({'error': '0', 'message': u'修改成功！'})
    return jsonify({'error': '-1', 'message': u'旧密码不正确。'})


@api.route('/users/star/')
@auth.login_required
def get_star_job():
    page = request.args.get('page', 1, type=int)
    pagination = g.current_user.followed.filter_by(status=1).paginate(
        page, per_page=20, error_out=False)
    star_jobs = pagination.items

    jobs = []
    for star in star_jobs:
        job = star.followed.to_json()

        job['alarm'] = star.alarm and star.alarm.strftime('%Y-%m-%d %H:%M');
        jobs.append(job)

    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_star_job', page=page - 1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_star_job', page=page + 1, _external=True)

    return jsonify({
        'jobs': jobs,
        'prev': prev,
        'next': next,
        'count': pagination.total
    })

